<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Banner_model extends CI_Model {
    public function getAllBanners($bizId) {
        $banners = array();
        $this->db->where('busiId', $bizId);
        $this->db->order_by('order', 'DESC');
        $this->db->order_by('id', 'DESC');
        $query = $this->db->get('banner');
        foreach ($query->result() as $row) {
            $banners[] = array(
                'id'     => $row->id,
                'busiId' => $row->busiId,
                'url'    => $row->url,
                'order'  => $row->order,
            );
        }

        return $banners;
    }

    public function addBanner($bizId, $url) {
        $sql   = "SELECT MAX(`order`) AS `order` FROM `banner` WHERE `busiId`={$bizId};";
        $query = $this->db->query($sql);
        $order = $query->row_array();
        if (!$order || !isset($order)) {
            $order = 0;
        } else {
            $order = $order['order'];
        }
        ++$order;

        $data = array(
            'busiId' => $bizId,
            'url'    => $url,
            'order'  => $order,
        );

        $this->db->insert('banner', $data);

        return true;
    }

    public function getBannerById($id) {
        $id    = intval($id);
        $sql   = "SELECT * FROM `banner` WHERE id={$id};";
        $query = $this->db->query($sql);
        $banner = $query->row_array();
        if (!$banner || !isset($banner)) {
            $banner = array();
        }

        return $banner;
    }

    public function delBanner($id) {
        $this->db->delete('banner', array('id' => $id));
        return true;
    }

    public function setBannerOrder($id, $order) {
        $id = intval($id);
        $this->db->where('id', $id);
        $data = array(
            'order' => $order,
        );

        $this->db->update('banner', $data);

        return true;
    }
}
